<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6" :xs="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>个人信息</span>
          </div>
          <div>
            <div class="text-center">
              <userAvatar />
            </div>
            <ul class="list-group list-group-striped">
              <li class="list-group-item">
                <svg-icon icon-class="user" />用户名称
                <div class="pull-right">{{ user.userName }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="phone" />手机号码
                <div class="pull-right">{{ user.phonenumber }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="email" />用户邮箱
                <div class="pull-right">{{ user.email }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="tree" />所属部门
                <div class="pull-right" v-if="user.dept">{{ user.dept.deptName }} / {{ postGroup }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="peoples" />所属角色
                <div class="pull-right">{{ roleGroup }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="date" />创建日期
                <div class="pull-right">{{ user.createTime }}</div>
              </li>
            </ul>
          </div>
          <el-card class="mt-4" v-if="latestMedal">
            <div slot="header" class="clearfix">
              <span>我的勋章</span>
            </div>
            <div class="medal-content">
              <el-card class="medal-card" @click.native="showMedalDetail(latestMedal)">
                <div class="medal-header">
                  <span class="medal-name">{{ latestMedal.medalName }}</span>
                </div>
                <img 
                  :src="`http://localhost:81/dev-api${latestMedal.medalImage}`" 
                  alt="勋章图片" 
                  class="medal-image"
                >
                <div class="medal-meta">
                  <span>获得时间：{{ latestMedal.createdTime | formatDate }}</span>
                </div>
              </el-card>
            </div>
          </el-card>
          <el-card v-else class="mt-4" style="min-height: 80px">
            <div class="text-center">暂无勋章</div>
          </el-card>
        </el-card>
      </el-col>
      <el-col :span="18" :xs="24">
        <el-card>
          <div slot="header" class="clearfix">
            <span>基本资料</span>
          </div>
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本资料" name="userinfo">
              <userInfo :user="user" />
            </el-tab-pane>
            <el-tab-pane label="修改密码" name="resetPwd">
              <resetPwd />
            </el-tab-pane>
          </el-tabs>
        </el-card>
        <!-- 新增徽章展示模块 -->
        <el-card class="mt-4">
          <div slot="header" class="clearfix">
            <span>已获得徽章</span>
          </div>
          <div class="medal-grid">
            <!-- 修正：将v-for和key直接应用于el-tooltip组件 -->
            <el-tooltip 
              v-for="medal in allMedals" 
              :key="medal.id"
              :content="medal.description" 
              placement="top" 
              effect="light"
              :enterable="true"
              class="medal-tooltip"
            >
              <!-- 修正：移除多余的template标签 -->
              <el-card class="medal-card">
                <div class="medal-header">
                  <span class="medal-name">{{ medal.medalName }}</span>
                </div>
                <img 
                  :src="`http://localhost:81/dev-api${medal.medalImage}`" 
                  alt="勋章图片" 
                  class="medal-image"
                >
                <div class="medal-meta">
                  <span>获得时间：{{ medal.createdTime | formatDate }}</span>
                </div>
              </el-card>
            </el-tooltip>
          </div>
          <!-- 积分进度条 -->
          <el-tooltip 
            :content="'现在的积分：' + currentPoints"  
            placement="top" 
            effect="light"
            :enterable="true"
          >
            <el-progress 
              :percentage="currentPointsPercentage" 
              status="success" 
              class="progress-with-tooltip"
            ></el-progress>
          </el-tooltip>
        </el-card>
      </el-col>
    </el-row>
    
  </div>
</template>

<script>
import userAvatar from "./userAvatar";
import userInfo from "./userInfo";
import resetPwd from "./resetPwd";
import { getUserProfile } from "@/api/system/user";
import { getMyMedals } from "@/api/system/usermedal";
import { getNextMedal } from "@/api/system/medal";
import { getCurrentPoints } from "@/api/system/points";

export default {
  name: "Profile",
  components: { userAvatar, userInfo, resetPwd },
  data() {
    return {
      user: {},
      roleGroup: {},
      postGroup: {},
      activeTab: "userinfo",
      latestMedal: null,
      allMedals: [],
      currentPoints: 0,
      currentPointsPercentage: 0
    };
  },
  created() {
    this.getUser();
    this.loadLatestMedal();
    this.loadAllMedals();
    this.loadCurrentPoints();
  },
  methods: {
    async showMedalDetail(medal) {
      try {
        const pointsRes = await getCurrentPoints();
        const currentPoints = pointsRes.data || 0;
        const nextRes = await getNextMedal(currentPoints);
        const nextMedal = nextRes.data;

        let msg = `<strong>${medal.description}</strong><br>`;
        msg += `<img src="http://localhost:81/dev-api${medal.medalImage}" alt="勋章图片" style="width: 100px; height: 100px; margin: 10px auto; display: block;">`;

        if (nextMedal) {
          const needed = nextMedal.pointsRequired - currentPoints;
          if (needed > 0) {
            msg += `哇哦，你已经很棒啦！再获取 <span style="color:red">${needed}</span> 积分就能解锁【${nextMedal.medalName}】勋章啦，加油冲呀！`;
          } else {
            msg += `太厉害啦！你已经满足解锁【${nextMedal.medalName}】的条件咯，快去领取属于你的荣耀吧！`;
          }
        } else {
          msg += "你简直就是超级王者！已经拥有最高等级勋章啦，继续保持这份优秀呀！";
        }

        this.$alert(msg, medal.medalName, {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "确定",
          customClass: "medal-dialog"
        });
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("获取勋章详情失败");
      }
    },
    async getUser() {
      const response = await getUserProfile();
      this.user = response.data;
      this.roleGroup = response.roleGroup;
      this.postGroup = response.postGroup;
    },
    async loadLatestMedal() {
      const { rows } = await getMyMedals();
      if (rows.length > 0) {
        const sortedMedals = rows.sort((a, b) => b.id - a.id);
        this.latestMedal = {
          ...sortedMedals[0],
          createdTime: new Date(sortedMedals[0].createdTime)
        };
      }
    },
    async loadAllMedals() {
      const { rows } = await getMyMedals();
      this.allMedals = rows.sort((a, b) => a.id - b.id);
    },
    async loadCurrentPoints() {
      const res = await getCurrentPoints();
      this.currentPoints = res.data || 0;
      const maxPoints = 500; // 可根据实际业务调整最高积分
      this.currentPointsPercentage = Math.min((this.currentPoints / maxPoints) * 100, 100);
    }
  },
  filters: {
    formatDate(time) {
      if (!time) return "";
      const date = new Date(time);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    }
  }
};
</script>

<style scoped>
.mt-4 {
  margin-top: 20px;
}

.medal-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 10px;
  padding: 15px;
}

.medal-card {
  border-radius: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  transition: transform 0.15s ease, box-shadow 0.15s ease;
  padding-bottom: 15px;
}

.medal-card:hover {
  transform: scale(1.01);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.12);
}

.medal-header {
  padding: 12px 15px;
  border-bottom: 1px solid #ebf0f5;
}

.medal-name {
  font-size: 14px;
  text-align: center;
  display: block;
  margin-bottom: 8px;
}

.medal-content {
  text-align: center;
  padding: 10px;
}

.medal-image {
  width: 60px;
  height: 60px;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  display: block;
  margin: 0 auto 10px;
}

.medal-meta {
  font-size: 12px;
  color: #666;
}

.el-card[style*="min-height: 80px"] {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #999;
}

.medal-dialog {
  width: 400px;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.medal-dialog.el-message-box__content {
  line-height: 1.6;
  font-size: 14px;
  color: #333;
}

.medal-dialog.el-message-box__title {
  font-weight: bold;
  font-size: 16px;
  color: #007BFF;
}

.medal-dialog.el-message-box__btns button {
  background-color: #007BFF;
  color: white;
  border: none;
  transition: background-color 0.3s ease;
}

.medal-dialog.el-message-box__btns button:hover {
  background-color: #0056b3;
}

/* 新增进度条tooltip样式 */
.progress-with-tooltip {
  margin: 0 15px; /* 调整进度条左右边距，使tooltip显示更舒适 */
}

/* 新增徽章tooltip样式 */
.medal-tooltip .el-tooltip__popper {
  max-width: 250px;
  padding: 0;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  border: 1px solid #ebf0f5;
}

.tooltip-medal-image {
  width: 80px;
  height: 80px;
  object-fit: contain;
  display: block;
  margin: 10px auto;
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.tooltip-medal-desc {
  padding: 0 15px 15px;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  text-align: center;
}
</style>